import {Component, OnInit} from '@angular/core';
import {UsedStorePService} from '../../used-store-p.service';
import {ActivatedRoute, Router} from '@angular/router';

enum STATUS {
  草稿 = 1,
  待审核,
  待打包,
  待出库,
  已出库,
  已签收,
  已取消,
  审核不通过,
  物流异常,
}

@Component({
  selector: 'app-out-store-detail',
  templateUrl: './out-store-detail.component.html',
  styleUrls: ['./out-store-detail.component.scss']
})
export class OutStoreDetailComponent implements OnInit {
  STATUS = STATUS;
  detail: any = {};
  outStoreTypes: any[] = [];

  constructor(
    private usedStorePService: UsedStorePService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
  ) {
  }

  async ngOnInit() {
    await this.usedStorePService.dictData('machine_inbound_type').then((res: any) => {
      if (res.code === 0) {
        this.outStoreTypes = res.data.list.records;
      }
    });
    await this.usedStorePService.outStoreDetail(this.activatedRoute.snapshot.queryParams?.id).then(res => {
      if (res.code === 0) {
        this.detail = res.data;
        this.detail.orderExpress = this.detail.orderExpress[0] || {};
        if (this.detail.orderExpress.expressTraces) {
          this.detail.orderExpress.expressTraces = JSON.parse(this.detail.orderExpress.expressTraces);
        }
      }
    });
  }

  outStoreTypeName(id: any) {
    let typeName = '未知';
    this.outStoreTypes.forEach((i: any) => {
      if (i.content * 1 === id * 1) {
        typeName = i.name;
      }
    });
    return typeName;
  }

  getCount(key: 'realValuation' | 'price') {
    let count = 0;
    if (this.detail.list.length) {
      count = this.detail.list.reduce((total: number, item: any) => {
        return total + (key === 'realValuation' ? ((item[key] || 0) + (item['aprc'] || 0) + (item['cprc'] || 0)) : (item[key] || 0));
      }, 0)
    }
    return count;
  }

  edit() {
    this.router.navigate(['/used-store/usedOutAdd'], {queryParams: {id: this.detail?.delivery?.id}});
  }

  back() {
    window.history.go(-1);
  }

  // 明细string
  returnSplicDetailed() {
    let list = this.detail?.list || [];
    let tempArr: Array<any>= [];

    if (list.length) {
      let modelArr: Array<any> = [];
      
      list.forEach((item: any) => {
        if (!modelArr.includes(item.modelId)) {
          modelArr.push(item.modelId);
          tempArr.push({
            modelId: item.modelId,
            modelName: item.modelName || '无名',
            modelNumber: 1
          })
        } else {
          let tempIndex = tempArr.findIndex((tag: any) => tag.modelId === item.modelId);
          tempArr[tempIndex].modelNumber += 1;
        }
      })
    }

    return list?.length ? "共" + list.length + "机器" + ' ' + tempArr.map((m: any) => m.modelName + '*' + m.modelNumber).join('、') : '';
  }
}
